/**
 * @description 现金流回溯
 * @author wangjianjun
 */

import React, { PureComponent } from 'react';
import { NoDataC, DATA_ENTRY, AdvancedSearch, ContentPackage, XYHorizontalChartsC, TableC, NoQueryC, SecondHeaderC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Divider, Spin } from 'antd';
import { depCopy } from '../../../utils/utils';
import { connect } from 'dva';
import style from './index.less';
import colorsAll from '../../../css/colors';
import moment from 'moment';
import 'moment/locale/zh-cn';
@Form.create()
@connect(({ backtracke, forecast, loading, globalM }) => ({
  backtracke,
  forecast,
  loading,
  globalM,
}))
export default class Backtracke extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      noQuery: true,
      search: {}, //查询条件存储
      columnsCash: undefined, //现金流表格数据
      dataSourceCash: undefined,
      currentPage: 1, //当前页
      numInPage: 10000, //每页数量,前台分页
      total: 0,
      current: 1,
      pageSize: 20,
      yAxis1: undefined, //bar图表数据
      series1: undefined,
      yAxis2: undefined,
      series2: undefined,
      flag: false,
      flag2: true,
      leftSpan: 12,
      rightSpan: 12,
      initStatus: undefined,
      checkEventType: '0',
      selInit1: [
        {
          value: '0',
          title: '全部',
          children: [
            { value: '1', title: '付息' },
            { value: '2', title: '到期' },
            { value: '3', title: '还本' },
          ],
        },
      ],
      legend: [], //图的所有标签
      legend1: [], //图左侧的标签
      legend2: [], //图右侧的标签
      newlegend1: [], //用来控制间隙
      newlegend2: [], //用来控制间隙
      color: [], //图的所有颜色
      color1: [], // 图左侧颜色
      color2: [], // 图右侧颜色
      renderColor: [], //用于图渲染下方 点击按钮
      gridRight: 0,
      gridLeft: 0,
    };
  }

  componentDidMount() {}

  //根据返回数据 获取legend、color、color1、color2、renderColor
  unique = (data) => {
    let legend = [];
    let legend1 = [];
    let legend2 = [];
    data.series1.map((item) => {
      legend1.push(item.name);
      legend.push(item.name);
    });
    data.series2.map((item) => {
      legend2.push(item.name);
      legend.push(item.name);
    });
    let newhash = [];
    for (var i = 0; i < legend.length; i++) {
      if (newhash.indexOf(legend[i]) == -1) {
        newhash.push(legend[i]); //图的所有标签
      }
    }
    let colors = [];
    let color = [];
    for (var i = 0; i < newhash.length; i++) {
      colors.push(colorsAll.echart[i]); //图的所有颜色
      color.push({ name: newhash[i], color: colorsAll.echart[i], status: '0' }); //用于图渲染下方 点击按钮
    }
    let color1 = [];
    data.series1.map((item1) => {
      color.map((item2) => {
        if (item1.name == item2.name) {
          color1.push(item2.color); // 图左侧颜色
        }
      });
    });
    let color2 = [];
    data.series2.map((item1) => {
      color.map((item2) => {
        if (item1.name == item2.name) {
          color2.push(item2.color); // 图右侧颜色
        }
      });
    });
    this.setState({
      legend: newhash,
      legend1: legend1,
      legend2: legend2,
      newlegend1: legend1,
      newlegend2: legend2,
      renderColor: color,
      color: colors,
      color1: color1,
      color2: color2,
    });
  };

  //拿图表数据
  getAllDate(value, type) {
    const { dispatch } = this.props;
    //如果是全部，需要转换
    if (value && value.eventType && value.eventType == '0') {
      value.eventType = ['DQ', 'FX', 'HB', 'XQ', 'MR', 'MC', 'RSG', 'SH', 'FH'];
    }
    //时间需要转换
    if (value && value.beginDate && value.endDate) {
      value.beginDate = moment(value.beginDate).format('YYYYMMDD');
      value.endDate = moment(value.endDate).format('YYYYMMDD');
    }

    //设置undefined,出现loading效果
    this.setState({
      columnsCash: undefined,
      dataSourceCash: undefined,
    });

    dispatch({
      type: 'backtracke/cashFlow',
      payload: {
        ...value,
      },
      callback: (data) => {
        this.unique(data);
        this.setState({
          flag: true,
          yAxis1: data.yAxis1,
          series1: data.series1,
          yAxis2: data.yAxis2,
          series2: data.series2,
        });
      },
    });

    dispatch({
      type: 'backtracke/cashFlowDetails',
      payload: {
        ...value,
      },
      callback: (data) => {
        data.dataSource.map((item, index) => {
          item.key = index;
        });
        this.setState({
          columnsCash: data.columns,
          dataSourceCash: data.dataSource,
          total: data.pageInfo.total,
        });
      },
    });
    // 获取汇总信息
    dispatch({
      type: 'backtracke/getAccount',
      payload: {
        ...value,
      },
    });
  }

  //分页
  onShowSizeChange = (current, size) => {
    this.setState({
      current: 1,
      pageSize: size,
    });
  };

  onPageChange = (page, pageSize) => {
    this.setState({
      current: page,
    });
  };

  //点击查询按钮刷新数据
  getSearchData = (e) => {
    const { dispatch } = this.props;
    const { numInPage, frequency } = this.state;
    //不就行操作如果查询条件不完整,提示用户，并且不就行任何操作
    if (!(e.eventType && e.beginDate && e.endDate && e.portfolioId)) {
      message.warning('请设置完整的查询条件！');
      return;
    }

    this.setState({
      currentPage: 1,
      search: e,
      noQuery: false, //点击查询后去掉noQuery图片，到正常状态
    });
    const value = {
      numInPage: numInPage,
      currentPage: 1,
      ...e,
    };
    this.getAllDate(value);
  };

  //点击重置按钮,清空搜索条件
  onClear = (e) => {
    this.setState({
      search: {},
    });
  };

  //判断是不是空数组
  checkArr = (obj) => {
    //检验数组
    if (obj && Array.prototype.isPrototypeOf(obj) && obj.length === 0) {
      return true;
    } else {
      return false;
    }
  };

  //数组删除指定元素
  removeArr = (Arr, item) => {
    let index = Arr.indexOf(item);
    if (index > -1) {
      Arr.splice(index, 1);
    }
  };

  //点击图表下方按钮
  selectBtn = (name) => {
    let tag = '';
    let newRenderColor = depCopy(this.state.renderColor);
    let copynewlegend1 = depCopy(this.state.newlegend1);
    let copynewlegend2 = depCopy(this.state.newlegend2);
    newRenderColor.map((item) => {
      if (item.name == name) {
        if (item.status == '0') {
          item.status = '1';
          tag = 'unselect';
        } else {
          item.status = '0';
          tag = 'select';
        }
      }
    });

    this.setState(
      {
        renderColor: newRenderColor,
      },
      () => {
        let i1 = this.state.legend1.findIndex((value) => value == name);
        let i2 = this.state.legend2.findIndex((value) => value == name);
        // 如果出存在，不可以删除
        if (i1 != -1) {
          this.state.ref1.setLegend(tag, name);
          //同步对legend1或者legend2 操作
          if (tag == 'unselect') {
            this.removeArr(copynewlegend1, name);
          } else {
            copynewlegend1.push(name);
          }
        }
        if (i2 != -1) {
          this.state.ref2.setLegend(tag, name);

          if (tag == 'unselect') {
            this.removeArr(copynewlegend2, name);
          } else {
            copynewlegend2.push(name);
          }
        }
      },
    );
  };

  //图标自定义提示信息
  toolTipFormat = (params) => {
    let str = `<div>`;
    str += `<div>${params[0].name}</div>`;
    let dataIndex = params[0].dataIndex;
    this.state.legend.map((item, index) => {
      let tempL = this.state.series1.filter((ele) => ele.name === item);
      let tempR = this.state.series2.filter((ele) => ele.name === item);
      let value = '';
      //左边：如果是回购要特殊处理
      if (tempL && tempL.length === 1) {
        if (params[0].name == '回购') {
          value = tempL[0].data[dataIndex] ? tempL[0].data[dataIndex].toFixed(4) : '--';
        } else {
          value = tempL[0].data[dataIndex] ? tempL[0].data[dataIndex].toFixed(4) : '';
        }
      } else {
        if (params[0].name == '回购') {
          value = '--';
        } else {
          value = '';
        }
      }
      //如果左边的值是空，就不要逗号
      value == '' ? (value += '') : (value += ',');
      //右边：如果是回购要特殊处理
      if (tempR && tempR.length === 1) {
        if (params[0].name == '回购') {
          tempR[0].data[dataIndex] ? (value = value + tempR[0].data[dataIndex].toFixed(4)) : (value = value + '--');
        } else {
          //如果右边没有值，把逗号去掉
          tempR[0].data[dataIndex] ? (value = value + tempR[0].data[dataIndex].toFixed(4)) : (value = value.substring(0, value.lastIndexOf(',')));
        }
      } else {
        if (params[0].name == '回购') {
          value = value + '--';
        } else {
          value = value.substring(0, value.lastIndexOf(','));
        }
      }
      //如果没有值不展示
      let newvalue = '';
      if (value != '' && value != '--,--') {
        newvalue = `<div style="border:1px solid ${colorsAll.echartItems.toolLable};width:10px;height:10px;border-radius:50%;background-color:${this.state.color[index]};margin-right:10px"></div>
                   ${item}： ${value} `;
      }
      str += `<div style="display:flex;align-items:center"> 
            ${newvalue}
            </div>
           `;
    });
    str += '</div>';
    return str;
  };

  render() {
    const { renderColor, columnsCash } = this.state;
    const {
      loading,
      backtracke: { accountData },
    } = this.props;
    const {
      globalM: { dataDictionary: selectData },
    } = this.props;

    //组装columns
    if (columnsCash) {
      columnsCash.map((item, key) => {
        if (item.key == 'inflowAmt' || item.key == 'outflowAmt') {
          item.type = 'money';
        }
      });
    }
    //组装字典数据
    let selInit1 = [];
    if (selectData && selectData.CASHFLOW_EVENTTYPE && selectData.CASHFLOW_WEIGHTSET) {
      selectData.CASHFLOW_BACK_EVENTTYPE.map((item) => {
        let data2 = {};
        data2.value = item.code;
        data2.title = item.value;
        selInit1.push(data2);
      });
    }
    let selInit = [
      {
        value: '0',
        title: '全部',
        children: selInit1,
      },
    ];
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioId',
          title: '组合名称',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          isMultiple: true,
        },
        {
          dataIndex: ['endDate', 'beginDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [moment().subtract(1, 'year'), moment().subtract(1, 'day')],
          hasDataED: moment().subtract(1, 'day'),
          onRef: (ref) => {
            this.RANGEDATE = ref;
          },
          self: this.RANGEDATE,
        },
        {
          dataIndex: 'eventType',
          title: '事件类型',
          type: DATA_ENTRY.TREESELECT,
          isMultiple: true,
          dataSource: selInit,
          initialValue: this.state.checkEventType,
          treeCheckable: true,
        },
      ],
      onQuery: (e) => this.getSearchData(e),
      onClear: (e) => this.onClear(e),
    };

    const liStyle = {
      listStyleType: 'none',
      float: 'left',
      marginRight: '15px',
      cursor: 'pointer',
    };

    let echartsDom = null;
    let checkseries1 = this.checkArr(this.state.series1);
    let checkseries2 = this.checkArr(this.state.series2);
    const deSelect = colorsAll.echartItems.deSelect;
    const deSelectText = colorsAll.echartItems.deSelectText;
    let DOM = renderColor.map((item, index) => (
      <li onClick={() => this.selectBtn(item.name)} style={liStyle} key={index}>
        <span className={style.spanL} style={{ backgroundColor: item.status == '0' ? `${item.color}` : `${deSelect}` }}></span>{' '}
        <span style={{ color: item.status == '0' ? `${deSelectText}` : `${deSelect}` }}>{item.name}</span>
      </li>
    ));
    return (
      <ContentPackage
        title='现金流回溯'
        contentHtml={
          <div className={style.bondDeviation}>
            <Row>
              <AdvancedSearch {...searchProps} />
            </Row>
            {this.state.noQuery == true ? (
              <div style={{ marginTop: '13px' }}>
                <NoQueryC />
              </div>
            ) : (
              <div>
                <div style={{ marginTop: '13px' }}>
                  <SecondHeaderC title='维度统计' />
                </div>
                <Spin style={{ height: '500px' }} spinning={loading.effects['backtracke/cashFlow'] == true} tip='加载中...'>
                  {/* 用来占位loading */}
                  {!this.state.flag && <div style={{ height: '500px', width: '100%' }}></div>}
                  {/* 俩表格都有数据 */}
                  {!checkseries1 && !checkseries2 && this.state.flag && (
                    <div className={style.bgcolor} style={{ paddingLeft: '10px', paddingTop: '20px' }}>
                      {' '}
                      <Row style={{ marginTop: '13px' }} gutter={16}>
                        <Col span={12} style={{ paddingLeft: '0px', paddingRight: '0px', position: 'relative' }}>
                          <span className={style.titleLsftCss}>现金流流出(万元)</span>
                          <XYHorizontalChartsC
                            colors={this.state.color1}
                            yAxis={this.state.yAxis1}
                            series={this.state.series1}
                            height={500}
                            type='stack'
                            showLegend={false}
                            gridLeft={100}
                            gridRight={this.state.gridRight}
                            containLabel={false}
                            onRef={(ref) => this.setState({ ref1: ref })}
                            showTooltipLabel={false}
                            toolTipFormat={(params) => this.toolTipFormat(params)}
                          />
                        </Col>
                        <Col span={12} style={{ paddingLeft: '0px', paddingRight: '0px', position: 'relative' }}>
                          <span className={style.titleRightCss}>现金流流入(万元)</span>
                          <XYHorizontalChartsC
                            colors={this.state.color2}
                            yAxis={this.state.yAxis2}
                            series={this.state.series2}
                            height={500}
                            width={'100%'}
                            type='stack'
                            showLegend={false}
                            yAxisPosition='right'
                            gridLeft={this.state.gridLeft}
                            gridRight={100}
                            containLabel={false}
                            onRef={(ref) => this.setState({ ref2: ref })}
                            showTooltipLabel={false}
                            toolTipFormat={(params) => this.toolTipFormat(params)}
                          />
                        </Col>
                      </Row>
                      <Row>
                        {' '}
                        <ul className={style.right} style={{ marginRight: '50px' }}>
                          {' '}
                          {DOM}
                        </ul>{' '}
                      </Row>{' '}
                    </div>
                  )}
                  {/* 左表没有数据，右表有数据 */}
                  {checkseries1 && !checkseries2 && (
                    <div className={style.bgcolor} style={{ paddingLeft: '10px', paddingTop: '20px' }}>
                      {' '}
                      <Row style={{ marginTop: '13px' }} gutter={16}>
                        <Col span={24} style={{ paddingLeft: '0px', paddingRight: '0px', position: 'relative' }}>
                          <span className={style.titleRightCss}>现金流流入(万元)</span>
                          <XYHorizontalChartsC
                            colors={this.state.color2}
                            yAxis={this.state.yAxis2}
                            series={this.state.series2}
                            height={500}
                            width={'100%'}
                            type='stack'
                            showLegend={false}
                            yAxisPosition='right'
                            onRef={(ref) => this.setState({ ref2: ref })}
                            showTooltipLabel={false}
                            toolTipFormat={(params) => this.toolTipFormat(params)}
                          />
                        </Col>
                      </Row>
                      <Row>
                        {' '}
                        <ul className={style.right} style={{ marginRight: '50px' }}>
                          {' '}
                          {DOM}
                        </ul>{' '}
                      </Row>{' '}
                    </div>
                  )}

                  {/* 左表有数据，右表没有数据 */}
                  {!checkseries1 && checkseries2 && (
                    <div className={style.bgcolor} style={{ paddingLeft: '10px', paddingTop: '20px' }}>
                      {' '}
                      <Row style={{ marginTop: '13px' }} gutter={16}>
                        <Col span={24} style={{ paddingLeft: '0px', paddingRight: '0px', position: 'relative' }}>
                          <span className={style.titleLsftCss}>现金流流出(万元)</span>
                          <XYHorizontalChartsC
                            colors={this.state.color1}
                            yAxis={this.state.yAxis1}
                            series={this.state.series1}
                            height={500}
                            type='stack'
                            showLegend={false}
                            onRef={(ref) => this.setState({ ref1: ref })}
                            showTooltipLabel={false}
                            toolTipFormat={(params) => this.toolTipFormat(params)}
                          />
                        </Col>
                      </Row>
                      <Row>
                        {' '}
                        <ul className={style.right} style={{ marginRight: '50px' }}>
                          {' '}
                          {DOM}
                        </ul>{' '}
                      </Row>{' '}
                    </div>
                  )}
                  {/* 俩表格都没有数据 */}
                  {checkseries1 && checkseries2 && (
                    <div>
                      <NoDataC />{' '}
                    </div>
                  )}
                </Spin>
                <div style={{ marginTop: '13px' }}>
                  <SecondHeaderC title='现金流明细' />
                </div>
                <div className={style.totalRow}>
                  <Row style={{ marginLeft: '10px' }}>
                    <Col span={1}>
                      <span>汇总&nbsp;:</span>
                    </Col>
                    <Col span={6}>
                      <span style={{ paddingLeft: '20px' }}>现金流流入（万元）&nbsp;&nbsp;{`${accountData.inflowAmt}`}</span>
                      <span className={style.shuxian}>
                        <Divider type='vertical' />
                      </span>
                    </Col>
                    <Col span={6}>
                      <span style={{ paddingLeft: '20px' }}>现金流流出（万元）&nbsp;&nbsp;{`${accountData.outflowAmt}`}</span>
                    </Col>
                  </Row>
                </div>
                <Row>
                  <Col span={24}>
                    <TableC
                      columns={columnsCash}
                      dataSource={this.state.dataSourceCash}
                      pageSize={this.state.pageSize}
                      current={this.state.current}
                      onShowSizeChange={this.onShowSizeChange}
                      onPageChange={this.onPageChange}
                      rowKey='key'
                    />
                  </Col>
                </Row>
              </div>
            )}
          </div>
        }
      />
    );
  }
}
